const Router = require('koa-router');
const router = new Router();
const tool = require('../../tools/tool')
const {db, QueryTypes} = require("../../models/db");
// 保存派单
router.post('/receipt/dopd', async ctx => {
    let user = ctx.user
    let tenantId = user.tenantId;
    let list = ctx.request.body
    if(list.length === 0) return ctx.err('没有收款列表')
    let batch = []
    let billIds = []
    list.map(row => {
        billIds.push(row.id)
        batch.push({
            tenantId,
            buId: row.buId,
            buName: row.buName,
            billId: row.id,
            billNo: row.billNo,
            billDate: row.billDate,
            transType: row.transType,
            transTypeName: row.transTypeName,
            salesId: row.salesId,
            salesName: row.salesName,
            leftAmount: row.leftAmount,
            arrearsReal: row.arrearsReal,
            nowCheck: 0,
            yhAmount: 0,
            doId: row.doId,
            doName: row.doName,
            state: '收款中',
            cby: user.id,
            cbyName: user.name,
            createdAt: tool.getTime()
        })
    })
    let has = await db.query(`select * from receipt_pd where tenantId=${tenantId} and billId in (${billIds.join(',')}) 
                           and state=N'收款中' `,{type: QueryTypes.SELECT})
    if(has.length > 0) {
        let str = []
        for (let i = 0; i < has.length; i++) {
            str.push(has[i].billNo +'已在 ' + has[i].doName + ' 的派单中进行收款 ')
        }
        return  ctx.err(str.join(','))
    }
    await db.models['receiptPd'].bulkCreate(batch)
    return ctx.suc('已派单')
})

module.exports = router;
